package study.lxy.spring.springboot2.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import study.lxy.spring.springboot2.entity.LoginUser;
import study.lxy.spring.springboot2.utils.RedisUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtils redisUtils;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String url = request.getRequestURI();
        if(url.contains("swagger") || url.contains("api-docs")){
            return true;
        }
        /* 修改为通过redis缓存来进行登录过滤
        String loginUser = (String)request.getSession().getAttribute("loginUser");
        if(loginUser == null){
            response.sendRedirect(request.getContextPath()+"/login.html");
            return false;
        }
        */
        Cookie[] cookies =  request.getCookies();
        for(Cookie cookie : cookies){
            if("SESSION_ID".equals(cookie.getName())){
                LoginUser loginUser = (LoginUser) redisUtils.get("SESSION_ID:" + cookie.getValue());
                if(loginUser != null){
                    return true;
                }
            }
        }
        response.sendRedirect(request.getContextPath()+"/login.html");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
